<template>
  <t-modal
    :title="modalTitle"
    width="900px"
    :visible="visible"
    @ok="onSubmit()"
    @cancel="closeModal()"
    wrapClassName="add-modal-container"
    destroyOnClose
    v-bind:confirmLoading="confirmLoading"
    v-bind="footer"
  >
    <div class="curve-modal-body">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="false"
      >
        <div class="sub-title" v-if="pageOperate == 4">基本信息</div>
        <a-form-model-item
          label="专业"
          prop="major"
          :rules="{
            required: pageOperate == 4 || pageOperate == 3 ? false : true,
            message: '请选择专业',
          }"
        >
          <a-select
            placeholder="请选择"
            v-model="form.major"
            :disabled="isDisabled"
            showSearch
            allowClear
            :filter-option="filterOption"
          >
            <a-select-option
              :value="item.dicItemCode"
              v-for="item in majorSource"
              :key="item.dicItemCode"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          label="类别"
          prop="category"
          :rules="{
            required: pageOperate == 4 || pageOperate == 3 ? false : true,
            message: '请选择类别',
          }"
        >
          <a-select
            style="width: 100%"
            placeholder="请选择"
            v-model="form.category"
            showSearch
            :filter-option="filterOption"
            :disabled="isDisabled"
          >
            <a-select-option
              :value="item.dicItemCode"
              v-for="item in categorySource"
              :key="item.uuid"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          label="编号"
          prop="code"
          :rules="{
            required: pageOperate == 4 || pageOperate == 3 ? false : true,
            message: '请输入编号',
          }"
        >
          <a-input
            placeholder="请输入"
            v-model="form.code"
            :disabled="isDisabled"
          ></a-input>
        </a-form-model-item>
        <a-form-model-item
          label="设备/材料名称"
          prop="name"
          :rules="{
            required: pageOperate == 4 || pageOperate == 3 ? false : true,
            message: '请输入设备/材料名称',
          }"
        >
          <a-input
            placeholder="请输入"
            v-model="form.name"
            :disabled="isDisabled"
          ></a-input>
        </a-form-model-item>
        <a-form-model-item
          label="封样时间"
          prop="scheduledTime"
          :rules="{
            required: pageOperate == 4 || pageOperate == 3 ? false : true,
            message: '请选择封样时间',
          }"
        >
          <a-date-picker
            :disabled="isDisabled"
            style="width: 100%"
            v-model="form.scheduledTime"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-model-item>
        <a-form-model-item
          label="设计封样"
          prop="designSampleSealing"
          :rules="{
            required: pageOperate == 4 || pageOperate == 3 ? false : true,
            message: '请选择设计封样',
          }"
        >
          <bjUploadImg
            :viewMode="isDisabled"
            :count="30"
            v-model="form.designSampleSealing"
            @change="upLoadImage($event)"
            replaceField="url"
          ></bjUploadImg>
        </a-form-model-item>
        <a-form-model-item
          label="施工封样"
          v-if="
            [3, 4].includes(pageOperate) &&
              form.constructionSealingSample.length > 0
          "
        >
          <bjUploadImg
            :viewMode="true"
            v-model="form.constructionSealingSample"
            replaceField="url"
          ></bjUploadImg>
        </a-form-model-item>
        <a-form-model-item label="描述" prop="remark">
          <a-textarea
            placeholder="请输入"
            :rows="4"
            v-model="form.remark"
            :disabled="isDisabled"
          />
        </a-form-model-item>
        <a-form-model-item label="提交人">
          <a-input v-model="form.creator" disabled></a-input>
        </a-form-model-item>
        <a-form-model-item label="提交时间">
          <a-input v-model="form.createTime" disabled></a-input>
        </a-form-model-item>

        <!-- 审批 -->
        <template v-if="pageOperate == 4">
          <div class="sub-title">审批信息</div>
          <a-form-model-item
            label="审批结果"
            prop="operate"
            :rules="{
              required: true,
              message: '请选择审批结果',
            }"
          >
            <a-radio-group v-model="form.operate">
              <a-radio :value="2">
                通过
              </a-radio>
              <a-radio :value="3">
                驳回
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="审批意见" prop="reason">
            <a-textarea placeholder="请输入" :rows="4" v-model="form.reason" />
          </a-form-model-item>
        </template>
      </a-form-model>
    </div>
  </t-modal>
</template>

<script>
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
//上传图片
import bjUploadImg from "@/components/extendCustom/bj-upload-img";
import { getDicItemByCode } from "@/api/common.js";
import { getNowDateStr } from "@/utils/util";
import {
  saveSealSampleManage,
  detailSealSampleManage,
  approveSealSampleManage,
} from "@/api/design";
export default {
  components: {
    bjUploadImg,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    pageOperate: {
      type: [String, Number],
      default: "",
    },
    //1新增 2编辑 3查看 4审批
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },

  data() {
    return {
      modalTitle: "",
      isDisabled: false,
      confirmLoading: false,
      footer: {},
      form: {
        uuid: "",
        //专业
        major: undefined,
        //类别
        category: undefined,
        //编号
        code: "",
        //设备/材料名称
        name: "",
        //封样时间
        scheduledTime: "",
        //设计封样
        designSampleSealing: [],
        //施工封样
        constructionSealingSample: [],
        //描述
        remark: "",
        //审批结果
        operate: "",
        //审批意见
        reason: "",
        //提交时间
        createTime: "",
        //提交人
        creator: "",
      },
      rules: {},
      //类别
      categorySource: [],
      //专业
      majorSource: [],
    };
  },
  computed: {
    ...mapGetters(["nickname"]),
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          Promise.all([this.filterTitle(), this.getData()]);
        }
      },
      immediate: true,
    },
  },
  methods: {
    async getData() {
      //专业
      this.majorSource = await this.getDicCodeData("major");
      //节点类型
      this.categorySource = await this.getDicCodeData("category");
      if (this.pageOperate != 1) {
        this.getDetail();
      } else {
        this.form.creator = this.nickname;
        this.form.createTime = getNowDateStr(2);
      }
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //上传图片
    upLoadImage({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["designSampleSealing"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(
            this.form["designSampleSealing"][index],
            "dfsFileUuid",
            res.dfsFileUuid
          );
          this.$set(this.form["designSampleSealing"][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form["designSampleSealing"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["designSampleSealing"][index], "loading", false);
        });
    },

    //提交
    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { pageOperate } = this;
          //审批
          if (pageOperate == 4) {
            this.approveFormData();
          }
          //新增、编辑
          else {
            this.saveFormData();
          }
        }
      });
    },

    //新增、编辑
    saveFormData() {
      let { form } = this; //交底记录
      const files = form.designSampleSealing.map(
        ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
      );
      let formJson = {
        //专业
        major: form.major,
        //类别
        category: form.category,
        //编号
        code: form.code,
        //设备/材料名称
        name: form.name,
        //封样时间
        scheduledTime: form.scheduledTime,
        //设计封样
        designSampleSealing: JSON.stringify(files),
        //描述
        remark: form.remark,
      };
      //编辑
      if (form.uuid) {
        formJson.uuid = form.uuid;
      }
      this.confirmLoading = true;
      saveSealSampleManage(formJson)
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("操作成功", 1.5);
            this.closeModal();
            this.$parent.getTableData();
          } else {
            this.$message.error(res?.message ?? "操作失败");
          }
        })
        .catch((_) => {
          this.$message.error(_?.message ?? "操作失败");
        })
        .finally((_) => {
          this.confirmLoading = false;
        });
    },

    //审批
    approveFormData() {
      let { form } = this;
      let formJson = {
        uuid: form.uuid,
        operate: form.operate,
        reason: form.reason,
      };
      this.confirmLoading = true;
      approveSealSampleManage(formJson)
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success(res.message ?? "审批成功", 1.5);
            this.closeModal();
            this.$parent.getTableData();
          } else {
            this.$message.error(res?.message ?? "审批失败");
          }
        })
        .catch((_) => {
          this.$message.error(_?.message ?? "审批失败");
        })
        .finally((_) => {
          this.confirmLoading = false;
        });
    },

    //详情
    getDetail() {
      return new Promise((resolve, reject) => {
        let { uuid } = this.parameter;
        detailSealSampleManage({
          uuid,
        })
          .then((res) => {
            let { data } = res;
            this.form = {
              uuid: data?.uuid,
              //专业
              major: data.major,
              //类别
              category: data?.category,
              //编号
              code: data?.code,
              //设备/材料名称
              name: data?.name,
              //封样时间
              scheduledTime: data?.scheduledTime,
              //设计封样
              designSampleSealing: JSON.parse(
                data?.designSampleSealing ?? "[]"
              ),
              //施工封样
              constructionSealingSample: JSON.parse(
                data?.constructionSealingSample ?? "[]"
              ),
              //描述
              remark: data?.remark,
              //审批结果
              operate: 2,
              //审批意见
              reason: "",
              //提交人
              creator: data.creator,
              //提交时间
              createTime: data.createTime,
            };

            resolve();
          })
          .catch((_) => {
            this.form.designSampleSealing = [];
            this.form.constructionSealingSample = [];
            reject();
          });
      });
    },

    //重置表单
    resetForm() {
      this.form = {
        uuid: "",
        //专业
        major: undefined,
        //类别
        category: undefined,
        //编号
        code: "",
        //设备/材料名称
        name: "",
        //封样时间
        scheduledTime: "",
        //设计封样
        designSampleSealing: [],
        //施工封样
        constructionSealingSample: [],
        //描述
        remark: "",
        //审批结果
        operate: "",
        //审批意见
        reason: "",
        //提交人
        creator: "",
        //提交时间
        createTime: "",
      };
      this.$refs.ruleForm.clearValidate();
    },

    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },

    //标题
    filterTitle() {
      let { pageOperate } = this;
      switch (pageOperate) {
        //
        case 1:
          this.modalTitle = "新增";
          this.isDisabled = false;
          this.footer = {};
          break;
        //
        case 2:
          this.modalTitle = "编辑";
          this.isDisabled = false;
          this.footer = {};
          break;
        //
        case 3:
          this.modalTitle = "查看";
          this.isDisabled = true;
          this.footer = { footer: null };
          break;
        //
        case 4:
          this.modalTitle = "审批";
          this.isDisabled = true;
          this.footer = {};
          break;
        default:
          break;
      }
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .curve-modal-body {
    padding: 14px;
    box-sizing: border-box;
    max-height: 700px;
    overflow: hidden;
    overflow-y: auto;
    .ant-form-item {
      display: flex;
      .ant-form-item-label {
        flex-shrink: 0;
        width: 120px;
        white-space: pre-wrap;
        display: flex;
        justify-content: flex-end;
        line-height: 20px;
        margin-right: 2px;
        align-items: center;
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        overflow: hidden;
      }
    }
    .bj-upload-file {
      .choosed-file-warp {
        width: 100%;
      }
    }

    .sub-title {
      padding-left: 30px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      font-size: 18px;
      color: #525a5d;
      position: relative;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &::after {
        content: "";
        width: 3px;
        height: 16px;
        background: #1890ff;
        position: absolute;
        left: 14px;
        top: 50%;
        transform: translateY(-50%);
      }
      .ant-btn {
        margin-right: 0;
      }
    }
  }
}
</style>
